<template>
  <div v-if="liveInfo" @click="otherClick" class="theme-platform-custom c-bg-sgray" :class="{'theme-market': showMarketingBar}">
    <live-detail-cover ref="liveDetailCover"  :liveInfo="liveInfo" :moduleType="2" @spreadInvite="spreadInvite"></live-detail-cover>
    <article class="c-flex-grow1 c-flex-column c-contexty-scroll">
      <!-- 营销活动倒计时 -->
      <flash-sales-time-new v-if="showMarketingBar"
        :type="liveInfo.sales? 'isSale':liveInfo.isFriendHelper ? 'isFa' : liveInfo.bargain ? 'isBargain' : 'isCollage'"
        :price="liveInfo.sales ? liveInfo.sales.price : liveInfo.collage ? liveInfo.collage.captainPrice : liveInfo.bargain ? liveInfo.bargain.reservePrice : ''"
        :from="liveInfo.collage && liveInfo.collage.collageGroupType == 2 ? 'activity' : ''"
        :startTime="liveInfo.sales ? liveInfo.sales.sales.startTime : liveInfo.bargain ? liveInfo.bargain.startTime : liveInfo.collage ? liveInfo.collage.startTime : liveInfo.faStartAt"
        :endTime="liveInfo.sales ? liveInfo.sales.sales.endTime : liveInfo.bargain ? liveInfo.bargain.endTime : liveInfo.collage ? liveInfo.collage.endTime : liveInfo.faEndAt"
        :originalPrice="liveInfo.price"
        :stock="liveInfo.sales ? liveInfo.sales.balance: ''"
        :stockBargain="liveInfo.bargain && liveInfo.bargain.stock"
        :isLimit="liveInfo.sales && liveInfo.sales.limit == 0 || (liveInfo.bargain && liveInfo.bargain.isLimitStock == 2) ? false : true"
        :salesTag="liveInfo.sales && liveInfo.sales.sales.tags"
        :peopleNum="liveInfo.collage && liveInfo.collage.peopleNum"
        :isPreheat="liveInfo.bargain && liveInfo.bargain.isPreheat"
        :bargainStatus="liveInfo.bargain && liveInfo.bargain.status"
        :optimal="optimal"
        @showCoupon="showCoupon = true"
        @falshSalesTime="falshSalesTime"
        @finishFlashSales="finishFlashSales"
      >
      </flash-sales-time-new>
    </article>
    <personal-room-detail class="c-bg-white" ref="personRoomDetail" @showPackageList="showPackageList" @clickBackList="clickBackList" @changeIndex="changeIndex" @initData="initData" :backList='backList' :dataStatus='dataStatus' :showTryLook="showTryLook" :packageList="packageList" :companyAuth="companyAuth" :showCollocation="true" :isMarketing="isMarketing" :recRelateId="recRelateId" :recType="recType" @goCollageDetail="goCollageDetail"></personal-room-detail>
    <!-- <div class="c-pb100 c-bg-white c-mt20" v-if="packageList.length > 0 && companyAuth.enableComboModule == 1&&tabIndex==1">
      <package-index-com :showAll="true" :proType="15" :proId="liveInfo.lpId" :isHomePage="false" :packageList="packageList"></package-index-com>
    </div> -->
    <bottom-company-info v-if="companyAuth" :showInfo="companyAuth.enableShowInfo == 1 || companyAuth.liveAnnual == 1"
      :showDefaultText="companyAuth.liveAnnual == 1"></bottom-company-info>
    <!-- <more-device :positionType="2" :personalRoomIsLiving="liveInfo.liveStatus == 1 ? true : false" :prodInfo="{prodType: 180, prodId: liveId, socialRoomId: liveInfo.socialRoomId, detailId: liveInfo.detailInfo ? liveInfo.detailInfo.detailId : '', liveType: 6}" v-if="showMoreDevice"></more-device> -->
    <section v-if="tabIndex==5&&(liveInfo.isBuyed && liveInfo.permissionType != 45)" class=" c-flex-row c-pl32 c-pr24 c-aligni-center c-justify-sb c-bd-t1 c-hh88 c-pf c-p-b0 c-w100 c-maxw640 c-bg-white c-pz1">
      <div class="c-flex-grow1 c-flex-row c-aligni-center c-justify-end c-w0">
        <div class="theme-bg c-fc-white c-lh c-w0 c-flex-grow1 c-flex-row c-flex-center c-hh64 c-br36 c-fs28" @click="setComment">{{liveInfo.userHasComment?'修改评价':'我也要评价'}}</div>
      </div>
    </section>
    <bottom-buy-com
      v-else-if="(liveInfo.isSaleOnly == 0 && liveInfo.status != 3 && ((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0)) || (!liveInfo.isFriendHelper && !liveInfo.bargain || liveInfo.isInvitionCard)" :ckFrom="180"
      :isNeedPay="!liveInfo.isBuyed && ((liveInfo.isSaleOnly == 1 && (liveInfo.payType == 2 && liveInfo.price * 1 > 0)) || (liveInfo.isSaleOnly != 1 && liveInfo.isSaleTogether == 1))"
      @backPackage="backPackage"
      :showNotSale="liveInfo.isSaleOut == 0 && liveInfo.payType != 3 && liveInfo.status != 3 && liveInfo.isBuyed == 0 && liveInfo.price * 1 > 0"
      :notSale="liveInfo.isSaleOut == 0"
      :isNew="true"
      :isUserGroupUrl="((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45)||liveInfo.isBuyed == 0) && liveInfo.isUserGroup == 1 && liveInfo.isInUserGroups != 1&&liveInfo.userGroupUrl!=''"
      @invitePoster="invitePoster"
      @spreadInvite="spreadInvite"
      @handleClickDetail="handleClickDetail"
      @showBelongCourse="showPackageList">
      <div v-if="((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0) && liveInfo.isUserGroup == 1 && liveInfo.isInUserGroups != 1" class="c-bg-ccc c-fc-white c-lh c-w0 c-flex-grow1 c-flex-row c-flex-center c-hh64 c-br36 c-fs28">{{liveInfo.userGroupBottom?liveInfo.userGroupBottom:liveInfo.payType == 2 ? '仅指定用户可购买' : '仅指定用户可观看'}}</div>
      <div v-else-if="liveInfo.isSaleTogether==1&&liveInfo.isSaleOnly != 1&&!liveInfo.hasPermission" class="c-flex-column c-aligni-center theme-fc theme-bg-10 c-hh64 c-justify-sa c-w100 theme-bd1 c-br36" @click="showPackageList">
        <span class="c-fs28 c-lh">所属课程</span>
      </div>

      <div v-else class="btn-wrap c-fs28 c-lh c-w0 c-flex-grow1 c-flex-row">
        <div v-if="liveInfo.isSaleTogether==1&&(!isMarketing||(liveInfo.sales && liveInfo.sales.sales.status == 2))" class="c-flex-column c-hh64 c-aligni-center c-fc-white c-justify-center c-w100" @click="showPackageList">
          <span class="c-fs28 c-lh">所属课程</span>
        </div>
        <div v-if="((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45)||liveInfo.isBuyed == 0) && liveInfo.price * 1 > 0 &&liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType != -1" class="theme-bg c-fc-white c-lh c-w0 c-flex-grow1 c-flex-row c-flex-center c-hh64 c-fs24" @click="goCollageDetail(liveInfo.collage.groupId,liveInfo.collage.collageId)">
          拼团中...
        </div>
        <template v-else-if="((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45)||liveInfo.isBuyed == 0) && liveInfo.price * 1 > 0&&
          ((liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1)||
            (liveInfo.bargain != null && ((liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) || liveInfo.bargain.status == 2)))">
          <div class="c-flex-column c-hh64 c-aligni-center c-fc-white c-justify-center c-w100 theme-bg" @click="clickBuy">
            <span class="c-fs20 c-lh">{{getBuyBtnTitle}}</span>
            <span class="c-fs22 c-lh c-mt4"><span class="c-fs20">{{'￥' | iosPriceFilter('Live')}}</span>{{calculationPrice}}</span>
          </div>
          <div class="c-flex-column c-hh64 c-aligni-center c-fc-white c-justify-center c-w100" v-if="liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1" :class="liveInfo.collage.status == 2 ? 'theme-bg' : 'c-bg-d7'" @click="goBuy(-1,liveInfo.collage.collageId)">
            <span class="c-fs20 c-lh">发起拼团</span>
            <span class="c-fs22 c-lh c-mt4"><span class="c-fs20">{{'￥' | iosPriceFilter('Live')}}</span>{{Number(liveInfo.collage.captainPrice).toFixed(2)}}</span>
          </div>
          <template v-if="liveInfo.bargain != null && ((liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) || liveInfo.bargain.status == 2)&&liveInfo.bargain.userType == 1">
            <div class="c-hh64 c-flex-column c-aligni-center c-fc-white c-justify-sa c-w100 theme-bg" @click="handleClickBargainDetail(liveInfo.bargain.bargainId)">正在砍价</div>
          </template>
          <template v-if="liveInfo.bargain != null && ((liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) || liveInfo.bargain.status == 2)&&liveInfo.bargain.userType == -1">
            <div class="c-hh64 c-flex-column c-aligni-center c-fc-white c-justify-center c-w100" :class="(liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) ? 'c-bg-d7' : 'theme-bg'" @click="handleClickBargainDetail(liveInfo.bargain.bargainId)">
              <span class="c-fs20 c-lh">砍价享</span>
              <span class="c-fs22 c-lh c-mt4"><span class="c-fs20">{{'￥' | iosPriceFilter}}</span>{{Number(liveInfo.bargain.reservePrice).toFixed(2)}}</span>
            </div>
          </template>
        </template>
        <div v-else-if="!(((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0) && liveInfo.price * 1 > 0 && liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1)&& liveInfo.collage.userType == -1 ) && statusName"
          @click="clickBottomBtn(-1)"
          class="c-flex-column c-hh64 c-aligni-center c-fc-white c-justify-center c-w100"
          :class="statusClass">
          <span class="c-fs20 c-lh" v-if="((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0)&&this.liveInfo.payType==2">立即购买</span>
          <span v-else>{{statusName}}</span>
        </div>
      </div>
      <!-- <template v-else>
        <div class="c-flex-row c-hh64 c-br32 theme-bd1 c-ml16 c-w0 c-flex-grow1">
          <div v-if="liveInfo.isSaleTogether == 1" class="c-flex-column c-aligni-center theme-fc c-justify-sa c-w100" @click="showPackageList">
            <span class="c-fs28 c-lh">所属课程</span>
          </div>
          <div v-if="liveInfo.isSaleOnly==1&&((liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType != -1)||(((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0) && liveInfo.price * 1 > 0 && liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1)
            ||!(((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0) && liveInfo.price * 1 > 0 && liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1)&&statusName)" :class="liveInfo.isSaleTogether == 0?'c-br32':'c-br-br32 c-br-tr32'" class="c-flex-column c-aligni-center c-fc-white c-justify-sa c-w100 theme-bg-gradient c-p">
            <span v-if="liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType != -1" class="c-fs28 c-lh" @click="goCollageDetail(liveInfo.collage.groupId,liveInfo.collage.collageId)">
              拼团中...
            </span> -->
      <!-- <span class="c-flex-row c-hh64" v-else-if="liveInfo.isBuyed == 0 && liveInfo.price * 1 > 0 && liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1">
              <span class="c-flex-column c-aligni-center theme-fc c-justify-sa theme-bd1 c-ww196 c-br32 c-mr10 c-ml16" @click="clickBottomBtn(-1)">
                <span class="c-fs22 c-lh">{{'￥' | iosPriceFilter('Live')}}{{calculationPrice}}</span>
                <span class="c-fs20 c-lh">直接购买</span>
              </span>
              <span class="c-flex-column c-aligni-center c-fc-white c-justify-sa c-ww196 c-br32" :class="liveInfo.collage.status == 2 ? 'theme-bg' : 'c-bg-d7'" @click="goCollageDetail(-1,liveInfo.collage.collageId)">
                <span class="c-fs22 c-lh">{{'￥' | iosPriceFilter('Live')}}{{Number(liveInfo.collage.captainPrice).toFixed(2)}}</span>
                <span class="c-fs20 c-lh">发起拼团</span>
              </span>
            </span> -->
      <!-- <span @click.stop="popMarketingBuy" v-else-if="((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0)&& liveInfo.price * 1 > 0 &&
              ((liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1) || (liveInfo.bargain != null && ((liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) || liveInfo.bargain.status == 2)))" class="c-fs28 c-lh">
              购买
              <marketing-buy-btn v-if="liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1"
                :isCollage="true"
                :showMarketingBuyBtn="showMarketingBuyBtn"
                :calculationPrice="calculationPrice"
                :marketingPrice="Number(liveInfo.collage.captainPrice).toFixed(2)"
                :btnActivate="liveInfo.collage.status == 1 ? false : true"
                @clickBuyNow="clickBottomBtn(-1)"
                @marketingBuy="goBuy(-1,liveInfo.collage.collageId)">
              </marketing-buy-btn>
              <marketing-buy-btn v-if="liveInfo.bargain != null && ((liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) || liveInfo.bargain.status == 2)"
                :isBargain="true"
                :showMarketingBuyBtn="showMarketingBuyBtn"
                :calculationPrice="calculationPrice"
                :marketingPrice="Number(liveInfo.bargain.reservePrice).toFixed(2)"
                :btnActivate="(liveInfo.bargain.status == 1 && liveInfo.bargain.isPreheat == 1) ? false : true"
                :isBargaining="liveInfo.bargain.userType == 1 ? true : false"
                @clickBuyNow="clickBuy"
                @marketingBuy="handleClickBargainDetail(liveInfo.bargain.bargainId)">
              </marketing-buy-btn>
            </span> -->
      <!-- 有权限不在拼团中 -->
      <!-- <span v-else-if="!(((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0) && liveInfo.price * 1 > 0 && liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1) && liveInfo.collage.userType == -1)&&statusName"
              @click="clickBottomBtn(-1)"
              class="c-fs28 c-lh"
              :class="statusClass">
              {{statusName}}
            </span>
          </div>
          <div v-else-if="!((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0)&&statusName" :class="liveInfo.isSaleTogether == 0?'c-br32':'c-br-br32 c-br-tr32'" class="c-flex-column c-aligni-center c-fc-white c-justify-sa c-w100 theme-bg c-p"> -->
      <!-- 有权限 -->
      <!-- <span v-if="!((liveInfo.isBuyed == 1 && liveInfo.permissionType == 45) || liveInfo.isBuyed == 0)&&statusName"
              @click="clickBottomBtn(-1)"
              class="c-fs28 c-lh"
              :class="statusClass">
              {{statusName}}
            </span>
          </div>
        </div>
      </template> -->
    </bottom-buy-com>
    <!-- 关联弹窗 -->
    <related-list :isPersonal="1" :liveId="liveId" :showType="0" @closeCombo="closeCombo" :showCombo="showCombo"></related-list>
    <comfirm-com :showPassword="showPassword" :noticeText="noticeText" :text="'输入密码进入直播'" :placeholderText="'请输入密码'" @changePsw="changePsw" @closePassword="showPassword = false" @submitPassword="submitPassword"></comfirm-com>
    <share-masker :isShowShare="isShowShare" v-if="isShowShare" @closeShare="isShowShare=false;"></share-masker>
    <promote-income
      v-if="liveInfo && liveInfo.isSaleOut != 0"
      :showInvitionCard="!liveInfo.isFriendHelper && !liveInfo.bargain && liveInfo.isInvitionCard && !liveInfo.sales && !(liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1))"
      :showMarketingCard="liveInfo.isFriendHelper || (liveInfo.collage && (liveInfo.collage.status == 2 || liveInfo.collage.status == 1)) || liveInfo.sales || liveInfo.bargain"
      :prodId="liveId"
      :prodType="180"
      @goInvite="spreadInvite"
      @goMarketingPoster="invitePoster"
    ></promote-income>
    <!-- 推荐有礼 -->
    <recommend-present ref="recommendPresent"></recommend-present>
    <img v-if="showTryLook&&(liveInfo.liveStatus == 1||(liveInfo.liveStatus != 1&&liveInfo.isPlayBackAllowWatch))" @click="clickTryLook(liveInfo)" class="c-ww92 c-hh90 c-pf c-p-r24  c-p-b160 c-pz10" :src="require('@/assets/i/wap/live/tryLook.png')" alt="">
    <recommend-award v-if="liveInfo.recommend && liveInfo.recommend.isExist" :action="liveInfo.recommend && liveInfo.recommend.action"></recommend-award>
    <!-- 入学证书 -->
    <enrol-cer :isReceivedStudy="isReceivedBuy" ref="enrolcerCom" :bigType="2"></enrol-cer>
    <offical-account v-if="liveInfo && liveInfo.bargain" :showAccountQcode="showAccountQcode" :desc="officalDesc" :imgSrc="$addXossFilter(mpQrcode)" @hideDialog="hideDialog"></offical-account>
    <collage-grades ref="collageGrades" :relType="20" :refereeId="refereeId" :isRelForm="liveInfo.isRelForm && !liveInfo.hasFormLog" :extId="liveId" :bindPhoneSetting="bindPhoneSetting" :goodsRoomId="goodsRoomId" :recRelateId="recRelateId" :recType="recType" :dataInfo="liveInfo"></collage-grades>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import recommendPresent from '@/components/templates/recommendPresent'
import RecommendAward from "@/components/member/recommend/recommendAward.vue";
import officalAccount from '@/components/templates/common/officalAccount';
import LiveDetailCover from "@/components/templates/live/LiveDetailCover.vue";
import personalRoomDetail from '@/components/templates/live/personalRoomDetail.vue';
import bottomCompanyInfo from "@/components/templates/common/bottomCompanyInfo.vue";
import bottomBuyCom from "@/components/templates/common/bottomBuyCom.vue";
import ShareMasker from "@/components/templates/common/shareMasker.vue";
import ComfirmCom from "@/components/templates/common/comfirmCom.vue";
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";
import FlashSalesTimeNew from "@/components/templates/flashSalesTimeNew.vue";
import PromoteIncome from '@/components/templates/common/promoteIncome.vue';
import enrolCer from "@/components/templates/learnAndachCer/enrolCer.vue";
import { mapState } from "vuex";
import relatedList from '@/components/templates/live/relatedList';
import collageGrades from "@/components/templates/collage/collageGrades.vue";
const LIMIT = 10;
let _isClicking = false
let _isClickingflag = false
let pathFrom = '-1';
export default {
  name: "livePersonalDetail",
  components: {
    LiveDetailCover,
    FlashSalesTimeNew,
    personalRoomDetail,
    bottomCompanyInfo,
    bottomBuyCom,
    recommendPresent,
    ShareMasker,
    ComfirmCom,
    PromoteIncome,
    enrolCer,
    relatedList,
    RecommendAward,
    officalAccount,
    collageGrades
  },
  data() {
    return {
      tabIndex: 0,
      liveInfo: null,
      companyAuth: null,
      isShowShare: false,
      backList: [],
      dataStatus: 'HAS_MORE_DATA',
      statusName: '',
      statusClass: '',
      showPassword: false, //显示密码输入
      noticeText: "",
      pswIndex:-1,
      packageList: [],
      bindPhoneSetting: null,
      faStatus: 1,
      vipType: localStorage.getItem("vipType" + localStorage.getItem("userId")),
      recRelateId: "",
      recType: "",
      showAccountQcode:false,
      officalDesc: '关注我们后才可发起砍价哦',
      mpQrcode: '', //二维码
      isReceivedBuy:0,
      showMarketingBuyBtn:false,
      showCombo:false,
      showTryLook:false,
      isChainProd: false,
      cfg: JSON.parse(localStorage.getItem("cfg")),
      liveId:"",
      isWeChat: utilJs.isWeiXin(),
      goodsRoomId:'',
      optimal:null,
      chainInfo:'',
      isOpenIosGzhPay:true
    };
  },
  created() {
    utilJs.appShare(this);
    let reIdArr = window.location.href.split("refereeId=");
    if (reIdArr.length > 1 && reIdArr[1]) {
      let rId = reIdArr[1].split("&").length > 0 ? reIdArr[1].split("&")[0] : reIdArr[1];
      window.sessionStorage.setItem("refereeId", rId);
    }
  },
  mounted() { },
  computed: {
    ...mapState({
      showBindPhoneModal: (state) => state.oem_store.showBindPhoneModal
    }),
    showMarketingBar() {
      return this.liveInfo &&
        (
          this.liveInfo.sales ||
          (this.liveInfo.bargain && ((this.liveInfo.bargain.status == 1 && this.liveInfo.bargain.isPreheat == 1) || this.liveInfo.bargain.status == 2)) ||
          (this.liveInfo.collage && (this.liveInfo.collage.status == 2 || this.liveInfo.collage.status == 1)) ||
          this.liveInfo.isFriendHelper
        )
    },
     // 获取按钮专享价名称
    getBuyBtnTitle() {
      // 会根据是否开启ios支付区别文案展示
      let defaultTxt = '立即' + (this.isOpenIosGzhPay ? '购买' : '体验');
      if (this.optimal) {
        const agentName = utilJs.getCustNameMap();
        let btnTxt = '立即购买'
        let chainPrice = this.chainInfo && this.chainInfo.isChainProd ? (this.chainInfo.enableReorderDiscount == 1 && this.chainInfo.isReorder ? this.chainInfo.reorderBonus : this.chainInfo.enableOrderDiscount == 1 ? this.chainInfo.orderBonus : this.liveInfo.price) : this.liveInfo.price;
        let idDiscount = (this.vipType == 3 || this.vipType > 4) && this.liveInfo.commonProdInfo && this.liveInfo.commonProdInfo.agentDiscount < 100
          ? this.liveInfo.commonProdInfo.agentDiscount
          : (this.vipType == 4 && this.liveInfo.svipDiscount < 100)
            ? this.liveInfo.svipDiscount
            : (this.vipType == 2 && this.liveInfo.vipDiscount < 100)
              ? this.liveInfo.vipDiscount
              : 100
        let discountPrice = Number(this.liveInfo.price * idDiscount / 100).toFixed(2);
        if (this.chainInfo && this.chainInfo.isChainProd && Number(chainPrice) <= Number(discountPrice)) {
          let chainName = this.chainInfo.enableReorderDiscount == 1 && this.chainInfo.isReorder ? '复购' : (this.chainInfo.userType == 1 ? '普通用户' : this.chainInfo.userType2Name[this.chainInfo.userType])
          btnTxt = chainPrice != this.liveInfo.price && chainName ? chainName + '专享价' : defaultTxt;
        } else {
          btnTxt = discountPrice * 1 != this.liveInfo.price ? (this.vipType != 1 ? (this.vipType == 2 ? 'VIP专享价' : this.vipType == 4 ? 'SVIP专享价' : agentName[this.vipType] + '专享价') : defaultTxt) : defaultTxt;
        }
        if (this.liveInfo.sales && this.optimal.optimalPriceType == 101) {
          btnTxt = defaultTxt;
        }
        return btnTxt
      }
      return defaultTxt
    },
    calculationPrice() {
      let idDiscount = (this.vipType == 3 || this.vipType > 4) && this.liveInfo.commonProdInfo && this.liveInfo.commonProdInfo.agentDiscount < 100
          ? this.liveInfo.commonProdInfo.agentDiscount
          : (this.vipType == 4 && this.liveInfo.svipDiscount < 100)
            ? this.liveInfo.svipDiscount
            : (this.vipType == 2 && this.liveInfo.vipDiscount < 100)
              ? this.liveInfo.vipDiscount
              : 100
      let calculationPrice = Number(this.liveInfo.price * idDiscount / 100).toFixed(2)
      if (this.optimal) {
        // 链动价格
        let chainPrice = this.chainInfo && this.chainInfo.isChainProd ? (this.chainInfo.enableReorderDiscount == 1 && this.chainInfo.isReorder ? this.chainInfo.reorderBonus : this.chainInfo.enableOrderDiscount == 1 ? this.chainInfo.orderBonus : this.liveInfo.price) : this.liveInfo.price;
        // 当链动价格存在且链动价格跟常规身份价格对比时，如果链动小于或者等于身份价格取链动价格
        calculationPrice = this.chainInfo && this.chainInfo.isChainProd && Number(chainPrice) <= Number(calculationPrice) ? chainPrice : calculationPrice;
        if (this.liveInfo.isFriendHelper) {
          calculationPrice = Number(this.optimal.optimalPrice).toFixed(2);
        }
      }
      return calculationPrice;
    },
    //是否是营销活动
    isMarketing() {
      let isMarketing = this.liveInfo &&
      (this.liveInfo.sales || (this.liveInfo.bargain &&
      ((this.liveInfo.bargain.status == 1 &&
      this.liveInfo.bargain.isPreheat == 1) || this.liveInfo.bargain.status == 2)) ||
      (this.liveInfo.collage && (this.liveInfo.collage.status == 2 || this.liveInfo.collage.status == 1)) || this.liveInfo.isFriendHelper)
      return isMarketing
    },
  },
  watch: {},
  beforeRouteEnter(to, from, next) {
    next(vm => {
      pathFrom = from.path;
    });
  },
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      window.location.reload(true)
    }
  },
  methods: {
    setComment() {
      if (this.liveInfo.isRemove == 1) {
        this.$cjConfirm({
            showCancelButton: false,
            message: `您暂无评价权限！`,
        });
        return
      }
      this.$refs.personRoomDetail.setComment()
    },
    hideDialog() {
      this.showAccountQcode = false;
    },
    // 判断是否关注公众号
    checkUserIsFollowedMp() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        utilJs.getMethod(`${global.apiurl}bargains/getMpData?bargainId=${_this.liveInfo.bargain.bargainId}`,
          res => {
            resolve(res);
          },
          failRes => {
            reject(failRes)
          }
        )
      })
    },
    // 砍价跳转
    handleClickBargainDetail(bargainId) {
      if (this.liveInfo.bargain.status == 1) {
        this.$showCjToast({
          text: '活动未开始，暂不能砍价！',
          type: 'warn'
        });
        return;
      }
      this.checkUserIsFollowedMp().then(res => {
        if (res.threshold == 2 && res.isFollowedMp == 0) {
          this.mpQrcode = res.mpQrcode;
          this.showAccountQcode = true;
          return;
        }
        if (this.bindPhoneSetting && this.bindPhoneSetting.buyBind) {
          if (utilJs.goBindMobile()) return;
        }
        // 有关联表单，则跳到报名表单处
        if (this.liveInfo.isOpenFormCollection == 1 && this.liveInfo.collectPage == 1 && this.liveInfo.isRelForm && localStorage.getItem("showForm") == 1 && !this.liveInfo.hasFormLog) {
          this.$routerGo(this, "push", { path: '/homePage/form', query: {cId: -1, extId: this.liveId, ckFrom: global.ckFrom.personalLive, isFromInvite: 0, pId: -1, relType: 20, type: 1, recRelateId: this.recRelateId, recType: this.recType, joinType: 1} }); //type 1表示关联产品
          return;
        }
        if (this.liveInfo.bargain.status == 2) {
          this.$routerGo(this, "push", {
            path: "/homePage/bargain/bargainDetail",
            query: {
              bargainId: bargainId
            }
          });
        }
      })
    },
    judgeCompliance() {
      let postUrl = `${global.apiurl}Certificate/judgeCompliance?prodType=${global.ckFrom.personalLive}&prodId=${this.liveId}`;
      // enableStudyCard	number
      // 是否有设置学习证书1=是；0=否
      // isReceivedStudy	number
      // 是否已经领取了证书：1=是；0=否
      // isComplianceStudy	number
      // 是否达到学习证书发放条件：1=是；0否
      // studyHonorImage	string
      // 学习证书图片（如果领取了会有图片）
      // enableBuyCard	number
      // 是否有设置入学证书1=是；0=否
      // isReceivedBuy	number
      // 是否已经领取了入学证书：1=是；0=否
      // isComplianceBuy	number
      // 是否达到入学证书发放条件：1=是；0否
      // buyHonorImage	string
      // 入学证书证书图片（如果领取了会有图片）
      utilJs.getMethod(postUrl, res => {
        if (res.enableBuyCard == 1 && res.isComplianceBuy == 1 && res.isReceivedBuy == 0) {
          this.isReceivedBuy = res.isReceivedBuy
          let enrolCerLoca = global.ckFrom.personalLive + '-' + this.liveId
          if (JSON.parse(localStorage.getItem("enrolCer")) == enrolCerLoca) {
              return
          } else {
            this.$refs.enrolcerCom.drawNow('', this.liveId, global.ckFrom.personalLive)
          }
        }
      });
    },
    clickBackList(index) {
      if (this.showTryLook) {
        let detailId = this.backList[index].detailId || ''
        let reviewRelateId = this.backList[index].relateId || '';
        this.clickEnterRoom(detailId, reviewRelateId);
      } else {
        this.clickBottomBtn(index)
      }
    },
    clickTryLook(info) {
      console.log(111111)
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind) {
        if (utilJs.goBindMobile()) return;
      }
      console.log(222222)
      // let detailId = this.liveInfo.detailInfo && this.liveInfo.c || ''
      // let queryObj = {}
      if (this.liveInfo.liveStatus == 1) {
        // queryObj = {
        //   liveId: this.liveId,
        //   SocialRoomId: this.liveInfo.socialRoomId,
        // }
        let detailId = this.liveInfo.detailInfo.detailId
        this.clickEnterRoom(detailId, '')
      } else {
        this.$refs.personRoomDetail.changeType(2)
        // this.clickChangeTab(2)
        return
      }
      // if (detailId) {
      //   queryObj.detailId = detailId;
      // }
      // console.log(222222)
      // sessionStorage.setItem("livePathFrom", "room")
      // this.$routerGo(this, "push", {
      //     path: "/homePage/live/liveVHTryRoom",
      //     query: queryObj1,
      //   });
    },
    otherClick() {
      this.showMarketingBuyBtn = false;
    },
    popMarketingBuy() {
      this.showMarketingBuyBtn = true;
    },
    closeCombo() {
      this.showCombo = false;
    },
    showPackageList() {
      this.showCombo = true;
    },
    //活动海报
    invitePoster: function () {
      if (this.bindPhoneSetting && this.bindPhoneSetting.shareBind) {
        if (utilJs.goBindMobile()) return;
      }
      let ckFrom = global.ckFrom.personalLive;//this.ckFrom;
      let type = this.liveInfo.collage ? 3 : this.liveInfo.sales ? 2 : this.liveInfo.bargain ? 5 : 4;
      let cId = this.liveInfo.isFriendHelper ? this.liveInfo.faId : this.liveInfo.collage ? this.liveInfo.collage.collageId : this.liveInfo.bargain ? this.liveInfo.bargain.bargainId : this.liveInfo.sales.pId;
      let proId = this.liveId;
      this.$routerGo(this, "push", { path: '/homePage/spread/spreadPoster', query: { cId: cId, type: type, ckFrom: ckFrom, proId: proId } });
    },
    //拼团详情
    goCollageDetail: function (groupId, collageId) {
      if (this.liveInfo.collage.userType != -1 && this.liveInfo.collage.groupId != groupId) {
        this.$showCjToast({
          text: '您已在拼团中，不需要再去拼单啦！',
          type: 'warn'
        });
      } else {
        if (this.liveInfo.collage.status == 1) {
          this.$showCjToast({
            text: '活动未开始，暂不能拼团！',
            type: 'warn'
          });
        } else {
          let hfs = this.liveInfo.isOpenFormCollection == 1 && this.liveInfo.isRelForm && !this.liveInfo.hasFormLog;
          let pathQuery = {
            'groupId': groupId,
            'collageId': collageId,
            isRelForm: hfs,
            extId: this.liveId,
            relType: 20,
            recRelateId: this.$route.query.recRelateId,
            recType: this.$route.query.recType
          };
          if (this.goodsRoomId) {
            pathQuery.goodsRoomId = this.goodsRoomId;
          }
          this.$routerGo(this, "push", {
            path: "/homePage/collage/collageDetail",
            query: pathQuery
          });
        }
      }
    },
    //拼团详情
    goBuy: function (groupId, collageId) {
      if (this.liveInfo.collage.userType != -1 && this.liveInfo.collage.groupId != groupId) {
        this.$showCjToast({
          text: '您已在拼团中，不需要再去拼单啦！',
          type: 'warn'
        });
      } else {
        if (this.liveInfo.collage.status == 1) {
          this.$showCjToast({
            text: '活动未开始，暂不能拼团！',
            type: 'warn'
          });
        } else {
          //要加判断是否选择阶梯
          if (this.liveInfo.collage && this.liveInfo.collage.collageGroupType == 1 ) {
            this.$refs.collageGrades.goChoseBuy()
          } else {
            this.$refs.collageGrades.showBuy()
            // this.isShowBuy = true; //选择阶梯
          }
        }
      }
    },
     // // 限时购倒计时
    falshSalesTime(status) {
      if (this.liveInfo.sales) {
        this.liveInfo.sales.sales.status = status
      } else if (this.liveInfo.collage) {
        this.liveInfo.collage.status = status
      } else if (this.liveInfo.isFriendHelper) {
        this.faStatus = status;
      } else if (this.liveInfo.bargain) {
        this.liveInfo.bargain.status = status
      }
    },
    // // 限时购倒计时结束
    finishFlashSales(status) {
      if (this.liveInfo.sales) {
        this.liveInfo.sales.sales.status = status
      } else if (this.liveInfo.collage) {
        this.liveInfo.collage.status = status
      } else if (this.liveInfo.isFriendHelper) {
        this.faStatus = status;
      } else if (this.liveInfo.bargain) {
        this.getLiveInfo();
      }
      // 活动已结束，清空所有营销活动信息及状态
      if (status == -1) {
        this.liveInfo.sales = null;
        this.liveInfo.collage = null;
        this.liveInfo.isFriendHelper = false;
        this.initBottomStatus()
      }
    },
    //回退到上级(知识套餐),不支持单独售卖
    backPackage: function () {
      // if (this.liveInfo.liveType == 4 || this.liveInfo.liveType == 3) {
      //   this.$showCjToast({
      //     text: '语音直播，PPT直播正在维护，预计2月29号上线 ，如有需要，先用视频直播',
      //     type: 'warn'
      //   });
      //   return;
      // }
      if (pathFrom == "/homePage/column/columnDetail" || pathFrom == "/homePage/package/packageDetail") {
        this.$router.go(-1);
      } else {
        this.$routerGo(this, "push", {
          path: "/homePage/package/packageList",
          query: { noHighL: true, 'showAll': true, 'proType': 15, "proId": this.liveInfo.lpId }
        });
      }
    },
    //点击底部按钮
    clickBottomBtn(index) {
      this.pswIndex = index
      //回放已过期
      if (this.liveInfo.liveStatus == 4) {
        return;
      }
      if (((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.price * 1 > 0 && this.liveInfo.collage && (this.liveInfo.collage.status == 2 || this.liveInfo.collage.status == 1) && this.liveInfo.collage.userType != -1) {
        this.$cjConfirm({
            showCancelButton: false,
            message: `正在拼团中，暂不支持观看`,
        });
        return;
      } else if (this.pswIndex != -1 && this.liveInfo.collage && ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0)) {
        this.$cjConfirm({
            showCancelButton: false,
            message: `请先购买再观看回放`,
        });
        return;
      }
      if (((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.isUserGroup == 1 && this.liveInfo.isInUserGroups != 1) {
        this.$cjConfirm({
            showCancelButton: false,
            message: this.liveInfo.payType == 2 ? '仅指定用户可购买' : '仅指定用户可观看',
        });
        return;
      }
      if (this.liveInfo.isSaleOut == 0 && this.liveInfo.payType != 3 && this.liveInfo.status != 3 && ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.price * 1 > 0) {
        this.$showCjToast({
          text: '暂不支持售卖',
          type: 'warn'
        });
        return;
      }
      //已被移除
      if (this.liveInfo.isRemove == 1) {
        this.$cjConfirm({
            showCancelButton: false,
            message: `您暂无权限进入！请联系管理员！`,
        });
        return;
      }
      //点击底部按钮，没有被加入黑名单，没有直播中，有权限，回放显示并有回放
      if (this.pswIndex == -1 && !this.liveInfo.isRemove && this.statusName == '查看回放' && this.liveInfo.liveStatus == 0 && this.liveInfo.isPlayBackAllowWatch) {
        // this.clickChangeTab(2)
        this.$refs.personRoomDetail.changeType(2)
        return
      }
      //未绑定手机号
      if (
        (this.bindPhoneSetting && this.bindPhoneSetting.buyBind && ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.payType == 2) ||
        (this.bindPhoneSetting && this.bindPhoneSetting.passwordBind && this.liveInfo.payType == 3 && this.liveInfo.existPlayLog == 0 && ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0)) ||
        (this.bindPhoneSetting && this.bindPhoneSetting.getBind && ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType != 45) || this.liveInfo.isBuyed == 3 || (this.liveInfo.payType == 3 && this.liveInfo.existPlayLog == 1) || this.liveInfo.payType == 1))
      ) {
        let pathQuery = {};
        if (this.goodsRoomId) {
          pathQuery.goodsRoomId = this.goodsRoomId;
        }
        if (utilJs.goBindMobile()) return
      }
      if (this.liveInfo.isSaleOnly == 0 && this.liveInfo.status != 3 && ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.isSaleTogether == 1) {
        this.backPackage()
        return
      }
      //未购买 && 需要付费
      if (((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.payType == 2) {
        this.clickBuy();
        return;
      }
      if (this.liveInfo.payType == 3 && this.liveInfo.existPlayLog == 0 && this.liveInfo.isBuyed == 0) {
        this.clickEnterPwd()
        return;
      }
      //已购买
      if (this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType != 45 || this.liveInfo.isBuyed == 3 || (this.liveInfo.payType == 3 && this.liveInfo.existPlayLog == 1) || this.liveInfo.payType == 1) {
        let dId = this.liveInfo.detailInfo && this.liveInfo.detailInfo.detailId || '';
        let detailId = index != -1 ? this.backList[index].detailId : dId;
        let reviewRelateId = index != -1 ? this.backList[index].relateId : '';
        this.clickEnterRoom(detailId, reviewRelateId);
      }
    },
    //进入直播间
    async clickEnterRoom(detailId, reviewRelateId) {
      if (!detailId) {
        this.$showCjToast({
          text: '直播场次不存在',
          type: 'warn'
        });
        return;
      }
      //讲师身份不进入表单
      if (this.liveInfo.isOpenFormCollection == 1 && this.liveInfo.collectPage != 3 && this.liveInfo.userRole < 2 && this.liveInfo.isRelForm == true && localStorage.getItem("showForm") == 1 && !this.liveInfo.hasFormLog) {
        this.goForm()
        return;
      }
      if (_isClicking) {
        return;
      }
      _isClicking = true;
      //没在聊天室，需要加群
      //已经有进入过，直接进入直播间
      if (this.liveInfo.existPlayLog == 1) {
        if (this.liveInfo.notInSocialRoom == 1) {
          await this.addUserToSocailRoom();
        }
      } else {
        await this.addUserToSocailRoom();
      }
      if (this.liveInfo.isBuyed == 0 && this.showTryLook && (this.liveInfo.liveStatus == 1 || (this.liveInfo.liveStatus != 1 && this.liveInfo.isPlayBackAllowWatch))) {
        await this.setTryWatchUser()
      }
      //没有记录，则需要添加记录
      if (this.liveInfo.existPlayLog2 == 0) {
        await this.addLivePlayLog();
      }
      this.routerGoRoom(detailId, reviewRelateId);
    },
    setTryWatchUser() {
      return new Promise((resolve, reject) => {
        let postData = {
         "liveId": this.liveId,
         "moduleType":2
        };
        utilJs.postMethod(global.apiurl + "liveFlow/setTryWatchUser/" + this.liveId, postData, () => {
          resolve();
        }, () => {
          reject();
        });
      })
    },
    //提交密码
    submitPassword(inputPwd) {
      if (!inputPwd.trim()) {
        this.noticeText = "*密码错误";
        return;
      }
      if (_isClickingflag) {
        return;
      }
      _isClickingflag = true;
      utilJs.postMethod(`${global.apiurl}live/livePersonal/checkPassword/${this.liveInfo.lpId}`,
      {password:inputPwd}, res => {
          if (res == 0) {
            this.noticeText = "*密码错误";
          } else {
            this.showPassword = false;
            let dId = this.liveInfo.detailInfo && this.liveInfo.detailInfo.detailId || '';
            let detailId = this.pswIndex != -1 ? this.backList[this.pswIndex].detailId : dId;
            let reviewRelateId = this.pswIndex != -1 ? this.backList[this.pswIndex].relateId : '';
            if (this.pswIndex == -1 && this.liveInfo.liveStatus == 1) {
              this.clickEnterRoom(detailId, reviewRelateId);
            } else if (this.pswIndex != -1) {
              this.clickEnterRoom(detailId, reviewRelateId);
            } else if (this.liveInfo.existPlayLog != 1) {
              this.addUserToSocailRoom().then(res => {
                this.addLivePlayLog();
              })
            }
            this.liveInfo.existPlayLog = 1
            if (this.liveInfo.payType == 3 && this.liveInfo.liveStatus == 0) {
              //输入密码成功没有推流的时候因为不跳转，所以动态设置为有权限
              this.liveInfo.isBuyed = 1;
            }
            this.initBottomStatus()
          }
          _isClickingflag = false;
        },
        failRes => {
          _isClickingflag = false;
        }
      );
    },
    changePsw() {
      this.noticeText = "";
    },
    //显示密码输入框
    clickEnterPwd() {
      // }
      if (this.bindPhoneSetting && this.bindPhoneSetting.passwordBind) {
        if (utilJs.goBindMobile()) return;
      }
      // 有关联表单，则跳到报名表单处
      if (this.liveInfo.isOpenFormCollection == 1 && this.liveInfo.collectPage != 3 && this.liveInfo.userRole < 2 && this.liveInfo.isRelForm && localStorage.getItem("showForm") == 1 && !this.liveInfo.hasFormLog) {
        this.goForm()
        return;
      }
      this.noticeText = '';
      this.showPassword = true;
    },
    goForm() {
      let isGoBack = (this.liveInfo.isUserGroup == 1 && this.liveInfo.isInUserGroups != 1) || (this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType != 45) || this.liveInfo.payType == 3 || (this.isMarketing && !this.liveInfo.sales) || this.liveInfo.isSaleOnly == 0 ? 1 : 0;
      let pathQuery = {
        cId: -1,
        extId: this.liveInfo.lpId,
        ckFrom: global.ckFrom.personalLive,
        isFromInvite: 0,
        pId: -1,
        relType: 20,
        type: 1, //type 1表示关联产品
        recRelateId: this.$route.query.recRelateId,
        recType: this.$route.query.recType,
        joinType: 1, // jointype1表示密码加入
        isGoBack:isGoBack
      };
      this.$routerGo(this, "push", { path: '/homePage/form', query: pathQuery}); //type 1表示关联产品
      return;
    },
    routerGoRoom(detailId, reviewRelateId) {
      let queryObj = {
        liveId: this.liveId,
        SocialRoomId: this.liveInfo.socialRoomId,
      }
      if (detailId) {
        queryObj.detailId = detailId;
      }
      if (reviewRelateId) {
        queryObj.reviewRelateId = reviewRelateId;
      }
      if (this.ttId) {
        queryObj.ttId = this.ttId;
      }
      if (this.tlId) {
        queryObj.tlId = this.tlId;
      }
      let zhytUrl = this.$route.query.zhytUrl || '';
      if (zhytUrl) {
        queryObj.zhytUrl = zhytUrl;
      }
      if (this.$route.query.activityFrom == 1) {
        //扫码领奖
        queryObj.activityType = this.$route.query.activityType;
        queryObj.activityId = this.$route.query.activityId;
        queryObj.activityFrom = this.$route.query.activityFrom;
      }
      if (this.$isWxApp()) {
        _isClicking = false
        _isClickingflag = false
      }
      sessionStorage.setItem("livePathFrom", "room");
      this.$routerGo(this, "push", { path: `/homePage/live/liveVHRoom`, query: queryObj });
    },
    getRelatePackage() {
      return new Promise((resolve, reject) => {
        utilJs.getMethod(global.apiurl + "combos/showRel?proId=" + this.liveInfo.lpId + '&proType=15', (res) => {
            this.packageList = res;
            resolve();
        }, () => {
          reject();
        });
      })
    },
    addUserToSocailRoom() {
      return new Promise((resolve, reject) => {
        let postData = {
          "isCombos": this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 12 ? 61 : 0,
          "socialRoomId": this.liveInfo.socialRoomId,
          "refereeId": localStorage.getItem("refereeId")
        };
        utilJs.postMethod(global.apiurl + "social/addSocialRoom", postData, () => {
          _isClicking = false;
          resolve();
        }, () => {
          reject();
          _isClicking = false;
        });
      })

    },
    clickChangeTab(e) {
      this.tabIndex = e;
      if (this.tabIndex == 2) {
        this.initData()
      }
    },
    //邀请好友
    spreadInvite() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.shareBind) {
        if (utilJs.goBindMobile()) return;
      }
      if (this.liveInfo.isInvitionCard == 0) {
        this.isShowShare = true;
        return;
      }
      let extId = this.liveId;
      this.$routerGo(this, "push", {
        path: "/homePage/spread/spreadCustom",
        query: {
          ckFrom: global.ckFrom.personalLive,
          cId: 0,
          extId: extId
        }
      })
    },
    handleClickDetail() {
      let url = this.liveInfo.userGroupUrl
      if (url == '') {
        return
      }
      utilJs.locationHref(url);
    },
    //点击立即购买
    clickBuy() {
      let pathQuery = {};
      pathQuery = {
        extId: this.liveInfo.lpId,
        ckFrom: global.ckFrom.personalLive,
        isFromInvite: 0,
        recType: this.$route.query.recType,
        recRelateId: this.$route.query.recRelateId,
        pId: -1,
        relType: 20,
        type: 1, //type 1表示关联产品
        joinType: 1, // jointype1表示密码加入
      }
      let isInSales = this.liveInfo.sales && this.liveInfo.sales.sales.status == 2 && this.optimal && this.optimal.optimalPriceType == 101;
      let pId = isInSales ? this.liveInfo.sales.pId : null;
      if (isInSales) {
        pathQuery.pId = pId;
      }
      if (this.goodsRoomId) {
        pathQuery.goodsRoomId = this.goodsRoomId;
      }
      // 有关联表单，则跳到报名表单处
      if (this.liveInfo.isOpenFormCollection == 1 && this.liveInfo.collectPage == 1 && this.liveInfo.collectPage != 3 && this.liveInfo.isRelForm == true && this.liveInfo.hasFormLog != true && localStorage.getItem("showForm") == 1) {
        this.$routerGo(this, "push", { path: '/homePage/form', query: pathQuery });
        return;
      }

      this.$routerGo(this, "push", {
        path: "/homePage/course/coursePay",
        query: pathQuery
      });
    },
    //添加直播记录
    addLivePlayLog() {
      return new Promise((resolve) => {
        utilJs.postMethod(
        `${global.apiurl}live/livePersonal/addLivePlayLog/${this.liveId}`, {},
          (res) => {
            resolve();
          }
        );
      })
    },
    //作为分享页被推荐人进入
    isRecommendPage() {
      let recRelateId = this.recRelateId; //推荐人ID
      let recType = this.$route.query.recType || 0;; //推荐类型 1 访问 2 绑定 3 支付 //推荐类型 1 访问 2 绑定 3 支付
      let bindPhone = this.$route.query.bindPhone; //完成推荐绑定手机号
      let data = { relateId: recRelateId };
      if (recRelateId) {
        if (recType == 1) {
          this.$nextTick(() => {
            this.$refs.recommendPresent.completetRecommendTask(data);
          })
          // this.completetRecommendTask(data);
        } else if (recType == 2) {
          if (bindPhone) {
            data.mobile = localStorage.getItem("uMobile");
            this.$nextTick(() => {
              this.$refs.recommendPresent.completetRecommendTask(data);
            })
            // this.completetRecommendTask(data);
          } else if (!localStorage.getItem("uMobile")) {
            utilJs.goBindMobile({
                recRelateId: recRelateId,
                recType: recType,
                goLive: 1,
                liveId: this.liveId,
                ckFrom: global.ckFrom.live
            });
          } else {
            this.$cjConfirm({
              title: '领取失败',
              message: '您已绑定过手机号，不在推荐范围，无法领取奖励',
              showCancelButton: false,
            })
          }
        }
      }
    },
    //获取直播信息
    getLiveInfo(isFirst = 0) {
      let recRelateId = this.$route.query.recRelateId || ''; //推荐人ID
      let recType = this.$route.query.recType || ''; //推荐类型 1 访问 2 绑定 3 支付
      let url = `${global.apiurl}live/livePersonal/show/${this.liveId}?recRelateId=${recRelateId}&recType=${recType}&refereeId=${localStorage.getItem("refereeId")}&isSkeleton=1&time=${new Date().getTime()}`
      utilJs.getMethod(url, async (res) => {
        // 删除或无购买被下架
        if (res.data[0].status != 1) {
          this.$routerGo(this, "replace", {
            path: "/error/emptyPage",
            query: {
              from: "",
              info: "该直播已下架，请联系管理员！"
            }
          });
          return;
        }
        this.companyAuth = localStorage.getItem("companyAuth") && JSON.parse(localStorage.getItem("companyAuth"));
        this.liveInfo = res.data[0];
        this.liveInfo.isOpenFormCollection = 1
        this.optimal = this.liveInfo.optimal
        res.data[0].teachers = res.data.teachers;
        //是否可试看 =》非停售 && 有试看时间 && 已试看时间< 可试看时长 && 未购买 && 价格大于0 && 直播结束有回放
        let showTryLook = this.liveInfo.isSaleOut == 1 && this.liveInfo.watchTime && this.liveInfo.alreadyWatchTime * 1 < this.liveInfo.watchTime &&
        ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.payType == 2 && (this.liveInfo.liveStatus == 1 || this.liveInfo.isShowViewers);
        this.showTryLook = showTryLook

        this.showMoreDevice = (this.liveInfo.isBuyed || (this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType != 45)) && this.tabIndex == 0 && !showTryLook;
        // 拼团
        if (res.data[0].collage != null && this.companyAuth.enableCollage == 1) {
          let nt = (new Date()).getTime();
          let st = utilJs.getTimeByDate(res.data[0].collage.startTime);
          let et = utilJs.getTimeByDate(res.data[0].collage.endTime);
          if (nt >= st && nt < et && res.data[0].collage.status < 3) {
            // this.ckFrom = res.columnId == 0 ? global.ckFrom.collageCourse : global.ckFrom.collageColumn;
            this.liveInfo.collage.status = 2;
          } else if (nt < st && res.data[0].collage.status == 1) {
            // $this.ckFrom = res.columnId == 0 ? global.ckFrom.collageCourse : global.ckFrom.collageColumn;
            this.liveInfo.collage.status = 1;
          } else if (nt >= et && res.collage.status == 2) {
            this.liveInfo.collage.status = 3;
            this.liveInfo.collage = null;
            // $this.ckFrom = res.columnId == 0 ? global.ckFrom.course : global.ckFrom.column;
          } else {
            this.liveInfo.collage = null;
            // $this.ckFrom = res.columnId == 0 ? global.ckFrom.course : global.ckFrom.column;
          }
        } else if (res.data[0].sales != null && res.data[0].sales.status && (res.data[0].sales.limit == 0 || res.data[0].sales.balance > 0) && this.companyAuth.enableFlashSalesModule == 1) { //限时购
          let nt = (new Date()).getTime();
          let st = utilJs.getTimeByDate(res.data[0].sales.sales.startTime);
          let et = utilJs.getTimeByDate(res.data[0].sales.sales.endTime);
          if (nt >= st && nt < et && res.data[0].sales.sales.status > -1) {
            res.data[0].sales.sales.status = 2;
          } else if (nt < st && res.data[0].sales.sales.status == 1) {
            res.data[0].sales.sales.status = 1;
            // this.liveInfo.sales = null;
          } else if (nt >= et && res.data[0].sales.sales.status == 2) {
            res.data[0].sales.sales.status = -1;
            this.liveInfo.sales = null;
          } else {
            this.liveInfo.sales = null;
          }
        } else {
          this.liveInfo.sales = null;
          this.liveInfo.collage = null;
          // this.ckFrom = global.ckFrom.package;
        }
        this.initBottomStatus();
        await this.getRelatePackage();
        this.$nextTick(() => {
          this.initDetailInfo();
        })
        this.wechatShare();
        //扫码进来的时候
        if (this.$route.query.activityFrom == 1) {
          this.clickEnterRoom(this.$route.query.detailId, this.$route.query.reviewRelateId);
        }
        // ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0) && this.liveInfo.payType == 2 && this.liveInfo.status < 3;
          //是否从直播间进入该页面
          let isFromLiveRoom = pathFrom.includes('liveVHRoom') || (sessionStorage.getItem("livePathFrom") == "room");
          console.log(isFromLiveRoom, pathFrom)
          //不是从直播间进来的 && 是试看，直接跳转
          // let bindPhone = this.$route.query.bindPhone; //完成推荐绑定手机号
          //是否推荐有礼绑定手机号
          let isRecommend = recRelateId && (recType == 2 || recType == 1);
          //是否显示大转盘支付有礼活动
          let isShowTurntable = this.liveInfo.joinActivityInfo && this.liveInfo.joinActivityInfo.isShowDialog == 1;
          //是否被移除群聊
          let isRemove = this.liveInfo.isRemove == 1;
          //进入直播间是否需要绑定手机号
          let isNeedBindPhone = this.bindPhoneSetting && this.bindPhoneSetting.getBind;
          //是否关联表单
          let isGoForm = this.liveInfo.isOpenFormCollection == 1 && this.liveInfo.collectPage != 3 && this.liveInfo.userRole < 2 && this.liveInfo.isRelForm && localStorage.getItem("showForm") == 1 && !this.liveInfo.hasFormLog;
          //(付费 && 已购买) || (免费 && 单卖) || (关联售卖 && 已购买) || (加密 && 已进入)
          // let hasPermission = (info.isBuyed == 1 && info.payType == 2) || info.isBuyed == 3 || (info.payType == 1 && info.isSaleOnly == 1) || (info.isSaleOnly == 0 && info.isBuyed == 1) || (info.payType == 3 && info.existPlayLog == 1);
          let hasPermission = this.liveInfo.isBuyed >= 1;
          //直播是否开始 && 直播中、回放
          let isStartLive = this.liveInfo.status >= 1 && this.liveInfo.status < 3;
          if (isFirst == 1) {
            this.isRecommendPage();
          }
          let companyIdArr = ['36oewz', 'g9bk3e', '5qgedg', 'lj7l']; //这三个公司就算有直播视频简介也自动跳直播间
          let curCompanyId = localStorage.getItem('companyId');
          let setpersonal = ['79jee7', 'lj7l', '8rxm', '5r4y7']; //这三个公司就算有直播视频简介也自动跳直播间
          if (setpersonal.includes(curCompanyId)) { //中泰定制
            this.personalSet = true
          }
          let detailId = this.$route.query.detailId
          if (detailId) {
            window.sessionStorage.setItem('lookLiveId', this.liveId + '-' + detailId);
          } else if (this.liveInfo.status == 1) {
            detailId = this.liveInfo.detailInfo && this.liveInfo.detailInfo.detailId || '';
          }
          if (this.liveId + '-' + detailId == window.sessionStorage.getItem('lookLiveId')) {
            detailId = window.sessionStorage.getItem('lookLiveId').split('-')[1]
          }
          //不是从直播间进入的 && 无大转盘活动 && 未被移除群聊 && 不需要绑定手机号 && 不需要跳表单 && 直播已开始
          if (detailId && !this.showBindPhoneModal && !isRecommend && !isFromLiveRoom && !isShowTurntable && !isRemove &&
           !isNeedBindPhone && !isGoForm && isStartLive && hasPermission && this.liveInfo.isJumpToViewPage == 1 && (this.liveInfo.liveStatus == 1 || (this.liveInfo.liveStatus == 0 && this.liveInfo.isPlayBackAllowWatch)) &&
           (!this.liveInfo.videoIntroUrl || (companyIdArr.includes(curCompanyId) && this.liveInfo.videoIntroUrl))) {
            this.$loading.show({
              text: "正在进入直播间..."
            });
            this.clickEnterRoom(detailId, this.$route.query.reviewRelateId)
            return;
          }
          if (sessionStorage.getItem("livePathFrom")) {
            sessionStorage.removeItem("livePathFrom");
          }
          if (sessionStorage.getItem('liveGoBuy') == 1) {
            this.clickBuy()
            sessionStorage.removeItem('liveGoBuy');
          }
          this.judgeCompliance()
      }, () => {
        this.$routerGo(this, "replace", { path: '/' })
      });
    },
    //初始化底部购买按钮状态
    initBottomStatus() {
      // payType: 1免费 2付费 3加密
      // isBuyed: 是否有权限 0否 1是
      // isRemove: 购买后是否被移(拉入黑名单) 0否 1是除
      if (!this.liveInfo.isRemove) {
        //没有被加入黑名单
        if ((this.liveInfo.isBuyed == 1 && this.liveInfo.permissionType == 45) || this.liveInfo.isBuyed == 0 ) {
          //没有权限
           if (this.liveInfo.payType == 2) {
            //付费
            if (this.liveInfo.sales && this.liveInfo.sales.sales.status == 2) {
              this.statusName = '立即抢购';
            } else {
              this.statusName = '立即购买';
            }
            this.statusClass = this.showMarketingBar ? 'theme-bg c-fc-white' : 'theme-bg c-fc-white';
           } else if (this.liveInfo.payType == 3) {
            //加密
            this.statusName = '输入密码进入';
            this.statusClass = 'theme-bg c-fc-white';
          }
        } else {
          //有权限
          if (this.liveInfo.liveStatus == 1) {
            //直播中
            this.statusName = '进入直播间';
            this.statusClass = 'theme-bg c-fc-white';
          } else if (this.liveInfo.liveStatus >= 3) {
            //已过期
            this.statusName = '回放已过期';
            this.statusClass = 'c-bg-ccc c-fc-white';
          } else if (this.liveInfo.liveStatus == 0) {
            //没在直播
            if (this.liveInfo.isPlayBackAllowWatch) {
              this.statusName = '查看回放';
              this.statusClass = 'theme-bg c-fc-white';
            } else {
              this.statusName = '';
              this.statusClass = '';
            }
          }
        }
      } else {
        //加入黑名单（直接显示进入直播间，但是点击的时候有提示框提示）
        if (this.liveInfo.liveStatus == 1) {
          this.statusName = '进入直播间';
          this.statusClass = 'theme-bg c-fc-white';
        }
      }
    },
    //初始化详情组件
    initDetailInfo() {
      let info = {
        prodId: this.liveId, //直播id
        cover: this.liveInfo.cover,
        payType: this.liveInfo.payType,
        isShowRemind: this.liveInfo.isShowRemind, //是否开启预约
        liveStatus: this.liveInfo.liveStatus,
        videoIntroUrl: this.liveInfo.videoIntroUrl || '', //视频简介
        videoIntroM3u8: this.liveInfo.videoIntroM3u8 || '',
      }
      this.liveInfo.showMoreDevice = this.showMoreDevice;
      this.$refs.liveDetailCover.public_initDetail(info);
      this.$refs.personRoomDetail.public_initInfo(this.liveInfo);
    },

    //分享
    wechatShare() {
      let title = this.liveInfo.shareTitle;
      let shareImg = this.liveInfo.sales ? this.liveInfo.sales.shareImg : this.liveInfo.sharePic;
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?liveId=${this.liveId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.liveInfo.liveBrief;
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () {
      });
    },
    //手机端分享
    appShare() {
      let title = this.liveInfo.shareTitle;
      let shareImg = this.liveInfo.sales ? this.liveInfo.sales.shareImg : this.liveInfo.sharePic;
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?liveId=${this.liveId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.liveInfo.liveBrief;
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
    initPageData() {
      //页面变量
      this.optimal = null
      this.liveId = '';
      this.goodsRoomId = '';
      _isClicking = false;
      this._pageIndex = 1;
      this.tabIndex = 0;
      this.liveInfo = null;
      this.companyAuth = localStorage.getItem("companyAuth") && JSON.parse(localStorage.getItem("companyAuth"));
      this.isShowShare = false;
      this.backList = [];
      this.packageList = [];
      this.statusName = '';
      this.statusClass = '';
      this.recRelateId = this.$route.query.recRelateId;
      this.recType = this.$route.query.recType
      this.isChainProd = false;
      this.chainInfo = ''
      this.isOpenIosGzhPay = utilJs.isOpenIosGzhPay(global.ckFrom.personalLive);
    },
    changeIndex(tabIndex) {
      this.tabIndex = tabIndex
    },
    initData() {
      this._pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.backList = [];
      this.getPlayBackList();
    },
    //获取直播回放列表
    getPlayBackList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}live/livePersonal/getPlayBackList/${this.liveId}?limit=${LIMIT}&page=${this._pageIndex}`, (res) => {
        res.data = res.data.filter((item) => {
          item.duration = utilJs.timeTmpToStrTime(item.duration)
          return res.data
        });
        if (this._pageIndex == 1) {
          this.backList = res.data;
        } else {
          this.backList = [...this.backList, ...res.data];
        }
        if (res.data && (res.data.length < LIMIT)) {
          this.dataStatus = this._pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          this._pageIndex++;
        }
      }, failRes => {
        this.dataStatus = 'DATA_ERROR';
      });
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.backList.length > 0 && this.tabIndex == 2) {
          this.getPlayBackList();
        }
      });
    }
  },
  activated() {
    this.initPageData();
    setDocumentTitle("直播详情");
    this.liveId = this.$route.query.liveId;
    this.goodsRoomId = this.$route.query.goodsRoomId || '';
    getBindPhoneSetting(global.ckFrom.personalLive).then(res => {
      this.bindPhoneSetting = res;
    });
    utilJs.getChainInfo(global.ckFrom.personalLive, this.liveId).then(res => {
      this.chainInfo = res;
      this.isChainProd = res && res.isChainProd;
    });
    this.getLiveInfo(1);
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    window.removeEventListener('scroll', this.windowScrollFunction);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only  -->
<style scoped>
.btn-wrap > div:first-child {
  color: #ff8831;
  color: var(--mb7color);
  background-color: rgba(255, 99, 45, 0.1);
  background-color: var(--rgba10color);
  border-bottom-left-radius: 0.9rem;
  border-top-left-radius: 0.9rem;
  border: 1px solid #ff8831;
  border: 1px solid var(--mb7color);
}
.btn-wrap > div:nth-child(2) {
  color: white;
  background-color: rgba(255, 99, 45, 0.5);
  background-color: var(--rgba50color);
  border-top: 1px solid #ff8831;
  border-top: 1px solid var(--mb7color);
  border-bottom: 1px solid #ff8831;
  border-bottom: 1px solid var(--mb7color);
}
.btn-wrap > div:last-child {
  color: white;
  background-color: #ff8831;
  background-color: var(--mb7color);
  border-bottom-right-radius: 0.9rem;
  border-top-right-radius: 0.9rem;
  border: none;
  border-top: none;
  border-bottom: none;
}
.theme-market .btn-wrap > div:first-child {
  background-color: var(--rgba10MarketColor);
  border: 1px solid var(--marketColor1);
  color: var(--marketColor1);
}
.theme-market .btn-wrap > div:nth-child(2) {
  background-color: var(--rgba50MarketColor);
  border-top: 1px solid var(--marketColor1);
  border-bottom: 1px solid var(--marketColor1);
  color: var(--marketColor1);
}
.theme-market .btn-wrap > div:last-child {
  background-image: -webkit-linear-gradient(0, var(--marketColor2) 0%, var(--marketColor1) 100%);
  color: #FFFFFF;
}
</style>
